package com.example.jf.jfapp.utils;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

import com.example.jf.jfapp.bean.response.UpImageResponse;
import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by jf on 2017/7/28.
 */

public class UpFileUtils {
    private static final String TAG = "UpFileUtils";
    //需要上传的图片集合
    ArrayList<Uri> mImageUri;
    Context mContext;

    ArrayList<String> mSuccessImages = new ArrayList<>();//成功的图片链接

    int mCurrnetIndex = 0; //当前上传图片的下标

    public UpFileUtils(Context context, ArrayList<Uri> mIageUri) {
        mContext = context;
        this.mImageUri = mIageUri;
    }

    /**
     * 开始上传
     */
    public void start(UpStateListener upStateListener) {
        mUpStateListener = upStateListener;
        if (mImageUri != null && !mImageUri.isEmpty()) {
            upFile(mImageUri.get(mCurrnetIndex));
        }
    }

    /**
     * 重试
     */
    public void retry(){
        if (mImageUri != null && !mImageUri.isEmpty()) {
            upFile(mImageUri.get(mCurrnetIndex));
        }
    }



    public void upFile(Uri uri) {
        ((Activity)mContext).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mUpStateListener.onProgrees((mCurrnetIndex + 1));
            }
        });

        OkHttpClient okHttpClient = OkHttpUtils.getOkHttpClient();
        File imagePath = new File((getRealFilePath(mContext, uri)));
        MediaType IMAGETYPE = MediaType.parse("image/jpeg");
        RequestBody body = RequestBody.create(IMAGETYPE, imagePath);

        Request request = new Request.Builder()
                .post(body)
                .addHeader("X-LC-Id", "S5KdTtqGDUwpImMvQ6HAJYaL-gzGzoHsz")
                .addHeader("X-LC-Key", "NRPgCGiGxjbtGN2Bn0mlglrL")
                .addHeader("Content-Type", "image/*")
                .url("https://leancloud.cn:443/1.1/files/" + System.currentTimeMillis() + ".jpg")
                .build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mUpStateListener.onFailure((mCurrnetIndex + 1));
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                if (response.code() == 201) {
                    mCurrnetIndex = mCurrnetIndex + 1;
                    Log.e(TAG, "onResponse: 上传第" + mCurrnetIndex + "图片成功了");
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //成功
                    //图片上传成功后，再上传文本+图片链接等数据
                    UpImageResponse upImageResponse = new Gson().fromJson(result, UpImageResponse.class);
                    //Log.e(TAG, "onResponse: " + result);
                    mSuccessImages.add(upImageResponse.getUrl());

                    if (mCurrnetIndex < mImageUri.size()) {
                        Log.e(TAG, "onResponse: 开始上传第" + mCurrnetIndex + "图片");
                        upFile(mImageUri.get(mCurrnetIndex));
                    } else {
                        //成功，需要将成功的数据回调给使用者
                        if (mUpStateListener != null) {
                            mUpStateListener.onSucceed(mSuccessImages);
                        }

                    }
                } else {
                    //失败
                    mUpStateListener.onFailure((mCurrnetIndex + 1));
                }
            }
        });

    }

    UpStateListener mUpStateListener;

    public interface UpStateListener {
        //上传成功
        void onSucceed(ArrayList<String> successImages);
        //上传进度
        void onProgrees(int index);

        void onFailure(int index);



    }


    public static void upFile(Context context, Uri uri, Callback callback) {
        OkHttpClient okHttpClient = OkHttpUtils.getOkHttpClient();
        File imagePath = new File((getRealFilePath(context, uri)));
        MediaType IMAGETYPE = MediaType.parse("image/jpeg");
        RequestBody body = RequestBody.create(IMAGETYPE, imagePath);

        Request request = new Request.Builder()
                .post(body)
                .addHeader("X-LC-Id", "S5KdTtqGDUwpImMvQ6HAJYaL-gzGzoHsz")
                .addHeader("X-LC-Key", "NRPgCGiGxjbtGN2Bn0mlglrL")
                .addHeader("Content-Type", "image/*")
                .url("https://leancloud.cn:443/1.1/files/" + System.currentTimeMillis() + ".jpg")
                .build();
        okHttpClient.newCall(request).enqueue(callback);

    }


    public static String getRealFilePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

}
